const fs = require('fs');
const path = require('path');
const xml2js = require('xml2js');
const util = require('util');
const typeMapping = require('./typeMapping');

const parser = new xml2js.Parser();
const readFile = util.promisify(fs.readFile);
const writeFile = util.promisify(fs.writeFile);

async function readXmlFiles(dir, outputFile) {
    const directoryPath = path.join(__dirname, dir);
    let files = fs.readdirSync(directoryPath);
    files = files.filter(file => file.endsWith('.xml'));
    let allSql = '';

    for (const file of files) {
        const filePath = path.join(directoryPath, file);
        console.log(`Processing ${file}...`);
        const content = await readFile(filePath);
        const result = await parser.parseStringPromise(content);
        const sql = generateSql(result);
        allSql += sql + '\n\n';  // 累积SQL语句，并添加间隔
    }

    await writeFile(path.join(__dirname, outputFile), allSql);  // 写入单一文件
    console.log(`All SQL generated successfully into ${outputFile}`);
}

function generateSql(result) {
  const mapper = result.mapper;
  const tableName = mapper.sql.find(sql => sql.$.id === 'TableName')._.trim();  // 清理空白
  const primaryKey = mapper.resultMap[0].result[0].$.column; // 假设第一个result映射为主键
  const columns = mapper.resultMap[0].result.map(col => {
      const colType = typeMapping[col.$.jdbcType] || 'varchar(255)';
      const isPrimary = col.$.column === primaryKey ? ' NOT NULL AUTO_INCREMENT' : ' DEFAULT NULL';
      const comment = ` COMMENT '${col.$.property}'`;
      return `  \`${col.$.column}\` ${colType}${isPrimary}${comment}`;
  });

  const sql = `-- ${tableName}表
CREATE TABLE \`${tableName}\` (
${columns.join(',\n')},
PRIMARY KEY (\`${primaryKey}\`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='${tableName} 表';`;

  return sql;
}

// 调用函数，假设所有SQL语句保存在'combined_sql.sql'中
readXmlFiles('mapper', 'xml_to_sql_1.sql').catch(err => {
    console.error("Error occurred:", err);
});
